#include "StdAfx.h"
#include "Alog.h"
#include <stdio.h>
#include <wtypes.h>
#include <stdarg.h>
#include <tchar.h>

Alog * galog = NULL;

static void ( *pt_msg )( TCHAR * msg ) = NULL;
//static TCHAR mtext[1024];
//static TCHAR mmsg[2048];
//
//static FILE * mfile = NULL;
//static TCHAR mfilename[1024]="alog.txt";
//static int mfoutcnt = 0;
//static int mfouterr = 0;
////static CCriticalSection mcriticals;
//
//// 150603;
//static TCHAR mhead[1024] = "";
//
//static int mcreatesign = 0x12345678;
Alog::Alog()
{
	mcreatesign = 0x12345678;
}
Alog::~Alog()
{
}

void Alog::setHead( TCHAR *msg)
{
	_tcscpy(mhead, msg);
}

bool Alog::check()
{
	return ( mcreatesign == 0x12345678 ) ? true : false;
}

void Alog::outmsg(TCHAR *msg)
{
#ifdef _DEBUG
	_stprintf(mmsg,_T("%s%s"), mhead, msg);
	if ( pt_msg != NULL )
	{
		pt_msg( mmsg );
	}
	else
	{
		//printf( "%s", text );
		//TRACE("%s", text);
		OutputDebugString(mmsg); 
	}
#endif
}
void Alog::foutmsg(TCHAR *msg)
{
	//
	if( mfoutcnt > 0 )
		mfile = _tfopen(mfilename, _T("wa"));
	else
		mfile = _tfopen(mfilename, _T("w"));

	if( mfile == NULL)
	{
		mfouterr++;
	}
	else
	{
		mfoutcnt=1;

		_stprintf(mmsg,_T("%s%s"), mhead, msg);
		_ftprintf(mfile, _T("%s"), mmsg);
		fclose(mfile);
	}
}
void Alog::out( TCHAR *msg, ... )
{
#ifdef _DEBUG
	//if( !check() ) return;

	//
	TCHAR *text = mtext;

	va_list	argptr;
	va_start( argptr, msg );
	_vstprintf( text, msg, argptr);
	va_end(argptr);

	outmsg(text);
#endif
}
void Alog::fout(TCHAR * msg, ...)
{
	//if( !check() ) return;

	//mcriticals.Lock();

	if( mfouterr > 0) return;
	//
	va_list		argptr;
	TCHAR *text = mtext;

	va_start ( argptr, msg );
	_vstprintf ( text, msg, argptr);
	va_end (argptr);

	outmsg(text);
	foutmsg(text);

	//mcriticals.Unlock();
}

void Alog::s_setHead( TCHAR * msg)
{
	if( galog)
		galog->setHead(msg);
}
void Alog::s_out(TCHAR * msg, ...)
{
#ifdef _DEBUG
	//if( !check() ) return;
	if( galog)
	{
		//
		TCHAR *text = galog->mtext;

		va_list	argptr;
		va_start( argptr, msg );
		_vstprintf( text, msg, argptr);
		va_end(argptr);

		galog->outmsg(text);
	}
#endif
}
void Alog::s_fout( TCHAR * msg, ...)
{
	if( galog)
	{
		if( galog->mfouterr > 0) return;
		//
		va_list		argptr;
		TCHAR *text = galog->mtext;

		va_start ( argptr, msg );
		_vstprintf ( text, msg, argptr);
		va_end (argptr);

		galog->outmsg(text);
		galog->foutmsg(text);
	}
}